<template>
  <div class="notification-container">
    <!-- 通知图标和未读数量 -->
    <el-badge :value="displayUnreadCount" :hidden="displayUnreadCount === 0" class="notification-badge">
      <el-button 
        type="text" 
        @click="showNotifications = !showNotifications"
        class="notification-btn"
      >
        <el-icon><Bell /></el-icon>
      </el-button>
    </el-badge>

    <!-- 通知下拉面板 -->
    <div v-if="showNotifications" class="notification-panel">
      <div class="panel-header">
        <span>通知中心</span>
        <div class="header-actions">
          <el-button 
            type="text" 
            size="small" 
            @click="refreshNotifications"
            title="刷新通知"
          >
            <el-icon><Refresh /></el-icon>
          </el-button>
          <el-button 
            type="text" 
            size="small" 
            @click="markAllAsRead"
            v-if="displayUnreadCount > 0"
          >
            全部已读
          </el-button>
          <el-button type="text" @click="showNotifications = false">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>

      <div class="panel-content">
        <!-- 通知标签页 -->
        <el-tabs v-model="activeTab" class="notification-tabs">
          <el-tab-pane label="全部通知" name="all">
            <div v-if="allNotifications.length > 0" class="notification-list">
              <div 
                v-for="notification in allNotifications" 
                :key="notification.id" 
                :class="['notification-item', { 'unread': notification.isRead === 0 }]"
              >
                <div class="notification-icon" v-if="getNotificationIcon(notification.type)">
                  <el-icon>
                    <component :is="getNotificationIcon(notification.type)" />
                  </el-icon>
                </div>
                <img 
                  v-else-if="notification.type === 'FRIEND_REQUEST'"
                  :src="getAvatarUrl(notification.relatedUserId) || '/images/default-avatar.png'" 
                  :alt="notification.title" 
                  class="user-avatar"
                  @error="$event.target.src='/images/default-avatar.png'"
                >
                <div class="notification-content">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-message">{{ notification.content }}</div>
                  <div class="notification-time">{{ formatTime(notification.createTime) }}</div>
                  <div v-if="notification.type === 'FRIEND_REQUEST'" class="notification-actions">
                    <el-button 
                      size="small" 
                      type="primary" 
                      @click.stop="handleFriendRequest(notification.relatedId, true)"
                    >
                      同意
                    </el-button>
                    <el-button 
                      size="small" 
                      @click.stop="handleFriendRequest(notification.relatedId, false)"
                    >
                      拒绝
                    </el-button>
                  </div>
                </div>
                <!-- 已读按钮 -->
                <div class="notification-actions-right">
                  <el-button 
                    v-if="notification.isRead === 0"
                    size="small" 
                    type="primary" 
                    plain
                    @click.stop="markAsRead(notification.id)"
                    class="mark-read-btn"
                  >
                    标记已读
                  </el-button>
                  <span v-else class="read-status">已读</span>
                </div>
              </div>
            </div>
            <div v-else class="no-notifications">
              <el-icon class="no-data-icon"><DocumentRemove /></el-icon>
              <p>暂无通知</p>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="好友请求" name="friend">
            <div v-if="friendRequests.length > 0" class="notification-list">
              <div 
                v-for="request in friendRequests" 
                :key="request.id" 
                class="notification-item friend-request"
              >
                <img 
                  :src="request.avatar || '/images/default-avatar.png'" 
                  :alt="request.username" 
                  class="user-avatar"
                  @error="$event.target.src='/images/default-avatar.png'"
                >
                <div class="notification-content">
                  <div class="user-name">{{ request.username }}</div>
                  <div class="request-message">{{ request.remark || '请求添加您为好友' }}</div>
                  <div class="notification-actions">
                    <el-button 
                      size="small" 
                      type="primary" 
                      @click="handleFriendRequest(request.id, true)"
                    >
                      同意
                    </el-button>
                    <el-button 
                      size="small" 
                      @click="handleFriendRequest(request.id, false)"
                    >
                      拒绝
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="no-notifications">
              <el-icon class="no-data-icon"><DocumentRemove /></el-icon>
              <p>暂无好友请求</p>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="任务通知" name="task">
            <div v-if="taskNotifications.length > 0" class="notification-list">
              <div 
                v-for="notification in taskNotifications" 
                :key="notification.id" 
                :class="['notification-item', { 'unread': notification.isRead === 0 }]"
              >
                <div class="notification-icon">
                  <el-icon>
                    <component :is="getNotificationIcon(notification.type)" />
                  </el-icon>
                </div>
                <div class="notification-content">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-message">{{ notification.content }}</div>
                  <div class="notification-time">{{ formatTime(notification.createTime) }}</div>
                </div>
                <!-- 已读按钮 -->
                <div class="notification-actions-right">
                  <el-button 
                    v-if="notification.isRead === 0"
                    size="small" 
                    type="primary" 
                    plain
                    @click.stop="markAsRead(notification.id)"
                    class="mark-read-btn"
                  >
                    标记已读
                  </el-button>
                  <span v-else class="read-status">已读</span>
                </div>
              </div>
            </div>
            <div v-else class="no-notifications">
              <el-icon class="no-data-icon"><DocumentRemove /></el-icon>
              <p>暂无任务通知</p>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { 
  Bell, 
  Close, 
  DocumentRemove, 
  Check, 
  Warning, 
  CircleClose, 
  Clock,
  User,
  Refresh
} from '@element-plus/icons-vue';
import axios from '@/utils/axiosConfig';

// 响应式数据
const showNotifications = ref(false);
const activeTab = ref('all');
const friendRequests = ref([]);
const allNotifications = ref([]);
const unreadCount = ref(0);

// 计算属性
const taskNotifications = computed(() => {
  return allNotifications.value.filter(notification => 
    ['TASK_ACCEPTED', 'TASK_COMPLETED', 'TASK_CANCELLED', 'TASK_TIMEOUT'].includes(notification.type)
  );
});

// 显示的未读数量（完全依赖后端返回的数据）
const displayUnreadCount = computed(() => {
  console.log('显示未读数量 - 后端返回:', unreadCount.value);
  return unreadCount.value;
});

// 获取当前用户ID
const getCurrentUserId = () => {
  const token = localStorage.getItem('token');
  console.log('获取token:', token ? '存在' : '不存在');
  if (!token) return null;
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    console.log('解析token payload:', payload);
    // JWT标准中通常使用sub字段存储用户ID
    const userId = payload.userId || payload.sub;
    console.log('当前用户ID:', userId);
    return userId;
  } catch (error) {
    console.error('解析token失败:', error);
    return null;
  }
};

// 获取通知图标
const getNotificationIcon = (type) => {
  const iconMap = {
    'TASK_ACCEPTED': Check,
    'TASK_COMPLETED': Check,
    'TASK_CANCELLED': CircleClose,
    'TASK_TIMEOUT': Clock
    // 移除 'FRIEND_REQUEST': User，让好友请求显示真实用户头像
  };
  return iconMap[type];
};

// 用户头像映射（响应式）
const userAvatars = ref(new Map());

// 获取用户头像URL（同步函数，用于模板绑定）
const getAvatarUrl = (userId) => {
  if (!userId) return '/images/default-avatar.png';
  return userAvatars.value.get(userId) || '/images/default-avatar.png';
};

// 预加载用户头像（异步函数）
const preloadUserAvatar = async (userId) => {
  if (!userId || userAvatars.value.has(userId)) return;
  
  try {
    const response = await axios.get(`/auth/user/${userId}`);
    if (response.data.success && response.data.user) {
      const avatarUrl = response.data.user.avatar || '/images/default-avatar.png';
      userAvatars.value.set(userId, avatarUrl);
    } else {
      userAvatars.value.set(userId, '/images/default-avatar.png');
    }
  } catch (error) {
    console.error('获取用户头像失败:', error);
    userAvatars.value.set(userId, '/images/default-avatar.png');
  }
};

// 格式化时间
const formatTime = (timeString) => {
  if (!timeString) return '';
    try {
    // 处理不同的时间格式
    let time;
    if (typeof timeString === 'string') {
      // 如果是字符串，尝试解析
      if (timeString.includes('T')) {
        // ISO 格式：2024-01-15T10:30:00
        time = new Date(timeString);
      } else if (timeString.includes('-') && timeString.includes(':')) {
        // 后端标准格式：2024-01-15 10:30:00
        // 转换为ISO格式以确保正确解析
        const isoString = timeString.replace(' ', 'T');
        time = new Date(isoString);
      } else if (timeString.includes('-')) {
        // 只有日期：2024-01-15
        time = new Date(timeString + 'T00:00:00');
      } else {
        // 尝试直接解析
        time = new Date(timeString);
      }
    } else {
      // 如果是数字（时间戳）
      time = new Date(timeString);
    }
    
    // 检查时间是否有效
    if (isNaN(time.getTime())) {
      console.warn('无效的时间格式:', timeString);
      return '时间未知';
    }
    
    const now = new Date();
    const diff = now.getTime() - time.getTime();
    
    // 如果时间在未来，可能是时区问题
    if (diff < 0) {
      console.warn('时间在未来，可能存在时区问题:', timeString, '时间差:', diff);
      return '刚刚';
    }
    
    const seconds = Math.floor(diff / 1000);
    const minutes = Math.floor(seconds / 60);
    const hours = Math.floor(minutes / 60);
    const days = Math.floor(hours / 24);
    const weeks = Math.floor(days / 7);
    const months = Math.floor(days / 30);
    const years = Math.floor(days / 365);
    
    if (seconds < 30) return '刚刚';
    if (seconds < 60) return `${seconds}秒前`;
    if (minutes < 60) return `${minutes}分钟前`;
    if (hours < 24) return `${hours}小时前`;
    if (days < 7) return `${days}天前`;
    if (weeks < 4) return `${weeks}周前`;
    if (months < 12) return `${months}个月前`;
    if (years < 2) return `${years}年前`;
    
    // 超过2年的显示具体日期
    return time.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric'
    });
  } catch (error) {
    console.error('时间格式化错误:', error, '原始时间:', timeString);
    return '时间解析失败';
  }
};

// 获取所有通知
const fetchAllNotifications = async () => {
  try {
    const response = await axios.get('/notifications/list?page=1&size=50');
    if (response.data.success) {
      allNotifications.value = response.data.data || [];
      
      // 预加载好友请求的用户头像
      const friendRequestNotifications = allNotifications.value.filter(
        notification => notification.type === 'FRIEND_REQUEST' && notification.relatedUserId
      );
      
      for (const notification of friendRequestNotifications) {
        await preloadUserAvatar(notification.relatedUserId);
      }
    } else {
      console.error('获取通知列表失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取通知列表失败:', error);
  }
};

// 获取未读通知数量
const fetchUnreadCount = async () => {
  try {
    console.log('开始获取未读通知数量...');
    const response = await axios.get('/notifications/unread-count');
    console.log('未读通知数量响应:', response.data);
    if (response.data.success) {
      unreadCount.value = response.data.count || 0;
      console.log('未读通知数量:', unreadCount.value);
    } else {
      console.error('获取未读通知数量失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取未读通知数量失败:', error);
  }
};

// 获取待确认的好友请求
const fetchFriendRequests = async () => {
  try {
    const response = await axios.get('/friends/requests/pending');
    if (response.data.success) {
      friendRequests.value = response.data.data || [];
    }
  } catch (error) {
    console.error('获取好友请求失败:', error);
  }
};

// 标记单个通知为已读
const markAsRead = async (notificationId) => {
  try {
    console.log('标记通知为已读:', notificationId);
    const response = await axios.put(`/notifications/${notificationId}/read`);
    if (response.data.success) {
      ElMessage.success('已标记为已读');
      // 操作成功后刷新通知列表，确保获取最新状态
      await fetchAllNotifications();
      await fetchUnreadCount();
      console.log('通知状态已刷新，后端返回的未读数量:', unreadCount.value);
    } else {
      ElMessage.error(response.data.message || '标记失败');
    }
  } catch (error) {
    console.error('标记通知已读失败:', error);
    ElMessage.error('标记失败，请重试');
  }
};

// 标记所有通知为已读
const markAllAsRead = async () => {
  try {
    const response = await axios.put('/notifications/read-all');
    if (response.data.success) {
      ElMessage.success('已标记所有通知为已读');
      // 操作成功后刷新通知列表，确保获取最新状态
      await fetchAllNotifications();
      await fetchUnreadCount();
      console.log('所有通知已标记为已读，后端返回的未读数量:', unreadCount.value);
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('标记所有通知已读失败:', error);
    ElMessage.error('操作失败');
  }
};

// 处理好友请求
const handleFriendRequest = async (requestId, accept) => {
  try {
    const response = await axios.post('/friends/handle', {
      requestId,
      accept
    });
    if (response.data.success) {
      ElMessage.success(accept ? '已同意好友请求' : '已拒绝好友请求');
      await fetchFriendRequests();
      await fetchAllNotifications();
      await fetchUnreadCount();
      // 发送事件通知父组件更新好友列表
      if (accept) {
        window.dispatchEvent(new CustomEvent('friendRequestAccepted'));
      }
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('处理好友请求失败:', error);
    ElMessage.error('操作失败');
  }
};

// 获取所有数据
const fetchAllData = async () => {
  const userId = getCurrentUserId();
  if (!userId) return;
  
  await Promise.all([
    fetchAllNotifications(),
    fetchUnreadCount(),
    fetchFriendRequests()
  ]);
};

// 初始化通知数据
const initNotifications = () => {
  const userId = getCurrentUserId();
  if (!userId) return;
  
  console.log('=== NotificationCenter v2.0 - 无轮询版本 ===');
  console.log('初始化通知数据，用户ID:', userId);
  fetchAllData();
};

// 手动刷新通知
const refreshNotifications = async () => {
  console.log('手动刷新通知...');
  await fetchAllData();
  ElMessage.success('通知已刷新');
};

// 监听好友请求发送事件
const handleFriendRequestSent = () => {
  console.log('检测到好友请求发送，刷新通知...');
  // 延迟一下再刷新，确保后端已经处理完成
  setTimeout(() => {
    fetchAllData();
  }, 1000);
};

onMounted(() => {
  initNotifications();
  // 监听好友请求发送事件
  window.addEventListener('friendRequestSent', handleFriendRequestSent);
});

onUnmounted(() => {
  // 清理事件监听
  window.removeEventListener('friendRequestSent', handleFriendRequestSent);
});
</script>

<style scoped>
.notification-container {
  position: relative;
  display: inline-block;
}

.notification-badge {
  position: relative;
}

.notification-btn {
  padding: 12px;
  font-size: 20px;
  color: #606266;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 50%;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.notification-btn:hover {
  color: #409eff;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  transform: scale(1.1);
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.notification-badge .el-badge__content {
  background-color: #ff4757;
  border: 2px solid #fff;
  font-weight: bold;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

.notification-panel {
  position: absolute;
  top: 100%;
  right: 0;
  width: 420px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  max-height: 500px;
  overflow: hidden;
  backdrop-filter: blur(10px);
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e8eaed;
  font-weight: 700;
  color: #2c3e50;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px 12px 0 0;
  font-size: 16px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.notification-tabs {
  background: white;
}

.notification-tabs :deep(.el-tabs__header) {
  margin: 0;
  padding: 0 16px;
  background: #f8f9fa;
}

.notification-tabs :deep(.el-tabs__content) {
  padding: 0;
}

.notification-list {
  max-height: 350px;
  overflow-y: auto;
  padding: 4px 0;
}

.no-notifications {
  padding: 40px 20px;
  text-align: center;
  color: #95a5a6;
  font-size: 15px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  margin: 16px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.notification-item {
  display: flex;
  padding: 16px;
  border-bottom: 1px solid #f0f2f5;
  transition: all 0.3s ease;
  border-radius: 8px;
  margin: 8px;
  background: linear-gradient(135deg, #fafbfc 0%, #f8f9fa 100%);
  align-items: center;
}

.notification-item:hover {
  background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.notification-item.unread {
  background: linear-gradient(135deg, #fff3cd 0%, #ffeaa7 100%);
  border-left: 4px solid #f39c12;
}

.notification-item:last-child {
  border-bottom: none;
}

.user-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 16px;
  object-fit: cover;
  border: 3px solid #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.user-avatar:hover {
  transform: scale(1.1);
}

.notification-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.notification-content {
  flex: 1;
}

.user-name,
.notification-title {
  font-weight: 700;
  color: #2c3e50;
  margin-bottom: 6px;
  font-size: 16px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.request-message,
.notification-message {
  font-size: 13px;
  color: #7f8c8d;
  margin-bottom: 8px;
  line-height: 1.4;
}

.notification-time {
  font-size: 12px;
  color: #95a5a6;
  margin-bottom: 8px;
}

.notification-actions {
  display: flex;
  gap: 10px;
}

.notification-actions .el-button {
  border-radius: 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.notification-actions .el-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
}

.notification-actions .el-button--primary:hover {
  background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.notification-actions .el-button:not(.el-button--primary) {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  color: #6c757d;
  border: 1px solid #dee2e6;
}

.notification-actions .el-button:not(.el-button--primary):hover {
  background: linear-gradient(135deg, #e9ecef 0%, #dee2e6 100%);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 已读按钮样式 */
.notification-actions-right {
  display: flex;
  align-items: center;
  margin-left: 12px;
  flex-shrink: 0;
}

.mark-read-btn {
  border-radius: 20px;
  font-weight: 600;
  font-size: 12px;
  padding: 6px 12px;
  transition: all 0.3s ease;
  background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
  border: none;
  color: white;
}

.mark-read-btn:hover {
  background: linear-gradient(135deg, #218838 0%, #1ea085 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(40, 167, 69, 0.4);
}

.read-status {
  font-size: 12px;
  color: #6c757d;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 12px;
  border: 1px solid #dee2e6;
  font-weight: 500;
}
</style>